<?php declare(strict_types=1);
namespace App\Http\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Http\Message\ContentType;
use Swoft\Http\Server\Contract\MiddlewareInterface;

/**
 * @Bean()
 *
 */
class ControllerMiddleware implements  MiddlewareInterface
{

    /**
     * Process an incoming server request.
     *
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     *
     * @return ResponseInterface
     * @inheritdoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        /** @var  $ret \Swoft\Http\Message\Response */
        $ret=$handler->handle($request);
        $data=$ret->getData();
        if (is_object($data)){
            return  response(ContentType::JSON)->withContent(json_encode($data));
        }

//        $p2=NewProduct(10000,"中间件加入的商品");
//        $data[]=$p2;
      return  response(ContentType::JSON)->withData($data);
    }
}
